using System.Collections.Generic;
using System.Xml.Linq;
using iTextSharp.text;

namespace PocoReport
{
    public class Paragraph : Text
    {
        public override XNode Save()
        {
            XElement element = new XElement("Paragraph");
            element.SetAttribValue("Style", Style);
            foreach (IPart part in Parts)
            {
                element.Add(part.Save());
            }
            return element;
        }

        public override IElement GetPdfElement(Document document, Style parentStyle, Scope scope)
        {
            iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph();
            Style mergedStyle = PocoReport.Style.Merge(parentStyle, Style);
            foreach (IPart part in Parts)
            {
                IElement element = part.GetPdfElement(document, mergedStyle, scope);
                AddElement(element, document, paragraph);
            }
            return paragraph;
        }

        private static void AddElement(IElement element, Document document, ITextElementArray paragraph)
        {
            if(element is EmptyElement)
            {
                foreach (IElement chunk in element.Chunks)
                {
                    AddElement(chunk, document, paragraph);
                }
            }
            else if (element is PageBreakElement)
            {
                document.NewPage();
            }
            else
            {
                paragraph.Add(element);
            }
        }
    }
}